package com.vitaf.cash.app.utils

import android.graphics.Typeface
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.BackgroundColorSpan
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.SubscriptSpan
import android.text.style.SuperscriptSpan
import android.text.style.UnderlineSpan

class SpannableStringUtil private constructor() {

    companion object {
        fun create(): Builder {
            return Builder()
        }
    }

    class Builder {
        private var fullText: String = ""
        private val spans = mutableListOf<SpanInfo>()

        /**
         * 设置完整文本
         */
        fun setText(text: String): Builder {
            this.fullText = text
            return this
        }

        /**
         * 设置关键字和对应的样式
         */
        fun setKey(key: String): KeyBuilder {
            return KeyBuilder(this, key)
        }

        /**
         * 构建SpannableString
         */
        fun build(): SpannableString {
            val spannableString = SpannableString(fullText)
            spans.forEach { spanInfo ->
                val startIndex = fullText.indexOf(spanInfo.key)
                if (startIndex != -1) {
                    val endIndex = startIndex + spanInfo.key.length
                    spanInfo.spans.forEach { span ->
                        spannableString.setSpan(span, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
                    }
                }
            }
            return spannableString
        }

        /**
         * 构建SpannableStringBuilder（支持多个相同关键字）
         */
        fun buildWithMultipleOccurrences(): SpannableStringBuilder {
            val builder = SpannableStringBuilder(fullText)
            spans.forEach { spanInfo ->
                var startIndex = 0
                while (startIndex != -1) {
                    startIndex = fullText.indexOf(spanInfo.key, startIndex)
                    if (startIndex != -1) {
                        val endIndex = startIndex + spanInfo.key.length
                        spanInfo.spans.forEach { span ->
                            builder.setSpan(span, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
                        }
                        startIndex = endIndex
                    }
                }
            }
            return builder
        }

        internal fun addSpanInfo(spanInfo: SpanInfo) {
            spans.add(spanInfo)
        }
    }

    class KeyBuilder(private val builder: Builder, private val key: String) {
        private val spans = mutableListOf<Any>()

        /**
         * 设置文字颜色
         */
        fun setColor(color: Int): KeyBuilder {
            spans.add(ForegroundColorSpan(color))
            return this
        }

        /**
         * 设置背景颜色
         */
        fun setBackgroundColor(color: Int): KeyBuilder {
            spans.add(BackgroundColorSpan(color))
            return this
        }

        /**
         * 设置字体大小（单位：sp）
         */
        fun setTextSize(spSize: Float): KeyBuilder {
            spans.add(AbsoluteSizeSpan(spSize.toInt(), true))
            return this
        }

        /**
         * 设置字体大小（单位：px）
         */
        fun setTextSizePx(pxSize: Int): KeyBuilder {
            spans.add(AbsoluteSizeSpan(pxSize))
            return this
        }

        /**
         * 设置相对字体大小（相对于默认字体的倍数）
         */
        fun setRelativeSize(proportion: Float): KeyBuilder {
            spans.add(RelativeSizeSpan(proportion))
            return this
        }

        /**
         * 设置加粗
         */
        fun setBold(): KeyBuilder {
            spans.add(StyleSpan(Typeface.BOLD))
            return this
        }

        /**
         * 设置斜体
         */
        fun setItalic(): KeyBuilder {
            spans.add(StyleSpan(Typeface.ITALIC))
            return this
        }

        /**
         * 设置加粗斜体
         */
        fun setBoldItalic(): KeyBuilder {
            spans.add(StyleSpan(Typeface.BOLD_ITALIC))
            return this
        }

        /**
         * 设置下划线
         */
        fun setUnderline(): KeyBuilder {
            spans.add(UnderlineSpan())
            return this
        }

        /**
         * 设置删除线
         */
        fun setStrikethrough(): KeyBuilder {
            spans.add(StrikethroughSpan())
            return this
        }

        /**
         * 设置上标
         */
        fun setSuperscript(): KeyBuilder {
            spans.add(SuperscriptSpan())
            return this
        }

        /**
         * 设置下标
         */
        fun setSubscript(): KeyBuilder {
            spans.add(SubscriptSpan())
            return this
        }

        /**
         * 设置点击事件
         */
        fun setClickable(clickableSpan: ClickableSpan): KeyBuilder {
            spans.add(clickableSpan)
            return this
        }

        /**
         * 设置自定义字体样式
         */
        fun setStyle(styleSpan: StyleSpan): KeyBuilder {
            spans.add(styleSpan)
            return this
        }

        /**
         * 设置自定义样式
         */
        fun setCustomSpan(span: Any): KeyBuilder {
            spans.add(span)
            return this
        }

        /**
         * 完成当前关键字的样式设置，返回Builder继续设置其他样式
         */
        fun complete(): Builder {
            builder.addSpanInfo(SpanInfo(key, spans.toList()))
            return builder
        }

        /**
         * 完成当前关键字的样式设置并构建最终结果
         */
        fun build(): SpannableString {
            builder.addSpanInfo(SpanInfo(key, spans.toList()))
            return builder.build()
        }

        /**
         * 构建支持多个相同关键字的SpannableStringBuilder
         */
        fun buildWithMultipleOccurrences(): SpannableStringBuilder {
            builder.addSpanInfo(SpanInfo(key, spans.toList()))
            return builder.buildWithMultipleOccurrences()
        }
    }

    data class SpanInfo(val key: String, val spans: List<Any>)
}

// 扩展函数，提供更便捷的使用方式
fun String.toSpannable(): SpannableStringUtil.Builder {
    return SpannableStringUtil.create().setText(this)
}